<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-29 14:08:57
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-22 11:44:17
 * @FilePath     : \rpms\src\views\document\scientific\software\index.vue
-->
<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="软件著作权" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <el-form
        :disabled="!isEdit"
        :model="model.formData"
        ref="formRef"
        @submit.prevent
        :rules="model.formRules"
        label-width="160px"
      >
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="成果来源" prop="type">
              <el-select
                style="width: 100%"
                v-model="model.formData.type"
                clearable
                placeholder="请选择"
                value-key="id"
              >
                <el-option
                  v-for="(item, index) in model.paperTypes"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="软件名称" prop="softwareName">
              <el-input v-model.trim="model.formData.softwareName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="model.formData.type === '1'">
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属项目" placeholder="请选择所属项目">
              <el-select
                style="width: 100%"
                v-model="model.formData.projectId"
                clearable
                placeholder="请选择"
                value-key="id"
                @change="handleSelected"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目编号" prop="projectNum">
              <el-input
                disabled
                v-model.trim="model.formData.projectNum"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="登记号" prop="signNum">
              <el-input v-model.trim="model.formData.signNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="开发完成日期" prop="devFinishTime">
              <el-date-picker
                style="width: 100%"
                v-model="model.formData.devFinishTime"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="date"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="权利取得方式" prop="copyrightAcquisition">
              <el-select
                v-model="model.formData.copyrightAcquisition"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  v-for="item in model.copyrightAcquisitions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="权利范围" prop="copyrightScope">
              <el-select
                v-model="model.formData.copyrightScope"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  v-for="item in model.copyrightScopes"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属公司主体" prop="principalCompanyCode">
              <el-select
                v-model="model.formData.principalCompanyCode"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  id="default-option"
                  v-for="item in principalCompanyArr"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="首次发表日期" prop="firstPublishTime">
              <el-date-picker
                style="width: 100%"
                v-model="model.formData.firstPublishTime"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="date"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="16" :lg="24">
            <el-form-item label="完成人" prop="copyrightOwner">
              <SelectForTable
                style="width: 100%"
                @change="changeCopyrightOwner"
                ref="authorSelectTable2"
                :value="model.formData.copyrightOwnerList"
              >
              </SelectForTable>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="16" :lg="24">
            <!-- <el-form-item label="著作权人" prop="author">
              <SelectForTable
                style="width: 100%"
                ref="authorSelectTable"
                @change="changeAuthor"
                :value="model.formData.authorList"
              >
              </SelectForTable>
            </el-form-item> -->

            <el-form-item label="著作权人" prop="author">
              <SelectForTable
                @change="changeAuthor"
                ref="authorSelectTable"
                :isCustom="true"
                :value="model.formData.peopleList"
                :className="'apply-select-table'"
              >
                <template v-slot:tableData="{ data }">
                  <el-select
                    style="width: 100%"
                    class="dept-2"
                    popper-class="dept"
                    v-model="publishDepts"
                    placeholder="单位选择"
                    clearable
                    multiple
                    filterable
                    remote
                    @remove-tag="handleRemovePartake"
                    :remote-method="remoteMethod"
                  >
                    <el-option :value="joinDeptList">
                      <el-tree
                        show-checkbox
                        :data="joinDeptList"
                        node-key="id"
                        ref="deptTreePartakeRef"
                        :props="defaultProps"
                        @check-change="handleCheckChangePartake"
                        check-on-click-node
                        check-strictly
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                      ></el-tree>
                    </el-option>
                  </el-select>

                  <el-table
                    v-if="data.length > 0"
                    :data="data"
                    border
                    :header-cell-style="{
                      background: '#eef1f6',
                      color: '#606266'
                    }"
                  >
                    <el-table-column type="index" label="序号" />
                    <el-table-column label="申请人或权利人类型">
                      <template #default="scope">
                        {{ scope.row.isDept === "0" ? "单位" : "人员" }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="name"
                      label="申请人或权利人"
                    ></el-table-column>
                    <el-table-column prop="name" label="是否内部">
                      <template #default="scope">
                        {{ scope.row.isEmp === "0" ? "否" : "是" }}
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </SelectForTable>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <el-upload
                name="uploadFile"
                multiple
                :accept="acceptTypes"
                :action="uploadComUrl"
                :headers="uploadHeaders"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :on-error="handleError"
                :file-list="defaultFileList"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <ecm-upload
                :files="defaultFileList"
                :docid="model.docid"
                @setFile="handleSuccess"
              ></ecm-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <approval ref="approvalRef"></approval>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
// import { useRoute } from "vue-router";
import { addSoftware, updateSoftware, getSoftwareById } from "/@/api/document";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import Approval from "../approval.vue";
import { postProjectList } from "/@/api/project";
import NotifMessage from "/@/utils/message/notification";
import SelectForTable from "/@/components/selectForTable/index.vue";
import { useRoute, useRouter } from "vue-router";
import { postDictList } from "/@/api/common";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
const approvalRef = ref<HTMLFormElement | null>(null) as any;
const defaultProps = {
  children: "children",
  label: "deptDescShrt",
  id: "id"
};
const router = useRouter();
const route = useRoute();
let model = reactive({
  docid: window["ecmDocType"].software,
  mode: "Add",
  dialogFormVisible: false,
  data: [],
  loading: false,
  paperTypes: [
    { name: "项目", value: "1" },
    { name: "非项目", value: "2" }
  ],
  formData: {
    apply: [],
    principalCompanyCode: null,
    type: "",
    projectNum: "",
    projectId: null,
    projectName: "",
    softwareName: "",
    signNum: "",
    devFinishTime: "",
    firstPublishTime: "",
    copyrightAcquisition: "",
    copyrightScope: "",
    attachment: [],
    author: [],
    authorList: [],
    peopleList: [], //软件著作全所属人
    copyrightOwner: [],
    copyrightOwnerList: []
  },
  copyrightScopes: [{ key: "1", label: "全部权利" }],
  copyrightAcquisitions: [
    { key: "1", label: "原始取得" },
    { key: "2", label: "继受取得" }
  ],

  formRules: {
    type: [{ required: true, message: "请选择成果来源", trigger: "change" }],
    softwareName: [
      { required: true, message: "请输入软件名称", trigger: "change" }
    ],
    signNum: [{ required: true, message: "请输入登记号", trigger: "change" }],
    devFinishTime: [
      { required: true, message: "请选择开发完成日期", trigger: "change" }
    ],

    copyrightAcquisition: [
      { required: true, message: "请选择权利取得方式", trigger: "change" }
    ],
    copyrightScope: [
      { required: true, message: "请选择权利范围", trigger: "change" }
    ],
    copyrightOwnerList: [
      { required: true, message: "请选择权利人", trigger: "change" }
    ],
    principalCompanyCode: [
      { required: true, message: "请选择所属公司主体", trigger: "change" }
    ],
    author: [{ required: true, message: "请选择著作权人", trigger: "change" }],
    attachment: [{ required: true, message: "请上传附件", trigger: "change" }]
  }
});
let publishDeptsCatch = ref([]);
let joinDeptList = ref([]);
let publishDepts = ref([]);
let authorSelectTable = ref(null);
let authorSelectTable2 = ref(null);
const formRef = ref<HTMLFormElement | null>(null) as any;
const deptTreePartakeRef = ref<HTMLElement | null>(null) as any;
let projectList = ref([]);
let defaultFileList = ref([]);
let principalCompanyArr = ref([]);

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.deptDescShrt.includes(value);
};
const remoteMethod = (query: string) => {
  deptTreePartakeRef.value!.filter(query);
};
const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
      model.formData.projectNum = data.list.find(
        el => el.id === model.formData.projectId
      )?.projectCode;
      model.formData.projectName = data.list.find(
        el => el.id === model.formData.projectId
      )?.projectName;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  model.formData.projectNum = target.projectCode;
  model.formData.projectName = target.projectName;
};

const changeCopyrightOwner = arr => {
  model.formData.copyrightOwner = arr;
};
// const changeAuthor = arr => {
//   model.formData.author = arr;
// };

// 选择著作权人
const changeAuthor = arr => {
  model.formData.author = arr.concat(publishDeptsCatch.value);
  publishDeptsCatch.value.map(el => {
    const index = authorSelectTable.value.participantList.findIndex(
      part => part.id === el.partakeUnitCode
    );
    if (index === -1) {
      authorSelectTable.value.participantList.push({
        id: el.partakeUnitCode,
        userId: el.partakeUnitCode,
        name: el.partakeUnitName,
        isEmp: el.isEmp,
        isDept: "0"
      });
    }
  });
};

const handleSuccess = res => {
  defaultFileList.value = res.file;
  model.formData.attachment = res.file;
  formRef.value.clearValidate();
};

const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;

  const participantList = authorSelectTable.value.participantList;
  const participantList2 = authorSelectTable2.value.participantList;
  model.formData.copyrightOwnerList = participantList2.map(el => {
    let deptName =
      el.name.indexOf("-") !== -1
        ? ""
        : el.deptName
        ? "-" + el.deptName
        : "-无";
    return {
      bizId: el.id,
      bizName: el.name + deptName,
      id: el.id,
      userId: el.id,
      name: el.name + deptName,
      companyName: el.deptName,
      department: el.deptName || el.department,
      deptName: el.deptName,
      isEmp: el.isEmp
    };
  });
  model.formData.authorList = participantList.map(el => {
    let deptName =
      el.name.indexOf("-") !== -1
        ? ""
        : el.deptName
        ? "-" + el.deptName
        : "-无";
    if (el.isDept) {
      deptName = "";
    }
    return {
      bizId: el.id,
      bizName: el.name + deptName,
      id: el.id,
      userId: el.id,
      name: el.name + deptName,
      companyName: el.deptName,
      department: el.deptName || el.department,
      deptName: el.deptName,
      isEmp: el.isEmp,
      isDept: el.isDept
    };
  });
  const params = JSON.parse(JSON.stringify(model.formData));
  params.attachment = JSON.stringify(params.attachment);
  delete params.author;
  delete params.copyrightOwner;
  delete params.peopleList;
  if (model.formData.type === "2") {
    params.projectId = null;
    params.projectNum = null;
  }
  if (+params.principalCompanyCode.dicCode > 2) {
    params["companyEntityCode"] = params.principalCompanyCode.dicCode;
    params["companyEntityName"] = params.principalCompanyCode.dicValue;
    params["companyEntityMaxCode"] = "3";
    params["companyEntityMaxName"] = "华润酒业";
  } else {
    params["companyEntityCode"] = params.principalCompanyCode.dicCode;
    params["companyEntityName"] = params.principalCompanyCode.dicValue;
    params["companyEntityMaxCode"] = params.principalCompanyCode.dicCode;
    params["companyEntityMaxName"] = params.principalCompanyCode.dicValue;
  }
  if (+params.principalCompanyCode.dicCode === 1) {
    params["companyEntityMaxName"] = "华润啤酒";
  }
  if (model.mode === "Add") {
    const { code, message, data } = await addSoftware(params);
    if (code === 200) {
      const businessId = data;
      model.formData.name = model.formData.softwareName;
      approvalRef.value.handleSubmit(businessId, model.formData, 57);
    } else {
      NotifMessage.error(message);
    }
  } else {
    const { code, message } = await updateSoftware(params);
    if (code === 200) {
      if (source && source === "back") {
        //驳回到第一步
        approvalRef.value.approvalSubmit(57);
      } else {
        //审批完之后，重新发起
        const businessId = route.query.rdScientificId;
        model.formData.name = model.formData.softwareName;
        approvalRef.value.handleSubmit(businessId, model.formData, 57);
      }
    } else {
      NotifMessage.error(message);
    }
  }
};

const goback = () => {
  router.push("/document/scientific?activeName=2");
};
const getData = async id => {
  defaultFileList.value = [];
  const { data } = await getSoftwareById(id);
  data.authorList.map(el => {
    el["userId"] = el.bizId;
    el["name"] = el.bizName;
    el["id"] = el.bizId;
    el["companyName"] = el.department;
  });

  data.copyrightOwnerList.map(el => {
    el["userId"] = el.bizId;
    el["name"] = el.bizName;
    el["id"] = el.bizId;
    el["companyName"] = el.department;
  });
  model.formData = data;
  model.formData.principalCompanyCode = {
    dicCode: data.companyEntityCode,
    dicValue: data.companyEntityName
  };
  model.formData.attachment = JSON.parse(model.formData.attachment as any);
  defaultFileList.value = model.formData.attachment;
  defaultFileList.value.map(el => {
    el["name"] = el.fileName;
  });

  model.formData.type = data.projectId ? "1" : "2";

  const peopleList = model.formData.authorList;
  model.formData.peopleList = peopleList.filter(el => el.isDept !== "0");
  peopleList
    .filter(el => el.isDept === "0")
    .map(el => {
      publishDeptsCatch.value.push({
        isDept: el.isDept,
        isEmp: el.isEmp,
        partakeUnitCode: el.id,
        partakeUnitName: el.name
      });
    });
  publishDepts.value = publishDeptsCatch.value.map(el => el.partakeUnitName);
  deptTreePartakeRef.value.setCheckedKeys(
    publishDeptsCatch.value.map(item => {
      return item.partakeUnitCode;
    })
  );
  // model.formData.projectNum = route.query.projectNum as any;
};

//获取内外部单位
const initDeptList = async () => {
  const { code, data } = await postDeptList({
    pageSize: 0
  });
  let deptList = [];
  if (code === 200) {
    deptList = data.map(item => {
      return {
        id: item.id,
        deptDescShrt: item.deptDescShrt,
        children: item.children,
        isEmp: "1"
      };
    });
  }
  let companyList = [];
  const res = await postSysCompanyList({
    pageSize: 0
  });
  if (res.code === 200) {
    res.data.list.map(el => {
      companyList.push({
        id: el.id,
        deptDescShrt: el.companyName,
        isEmp: "0"
      });
    });
  }

  joinDeptList.value = [
    {
      deptDescShrt: "内部单位",
      disabled: true,
      children: deptList,
      id: "0-0"
    },
    {
      deptDescShrt: "外部单位",
      disabled: true,
      children: companyList,
      id: "0-1"
    }
  ];
};

//移除选中著作权单位
const handleRemovePartake = event => {
  publishDeptsCatch.value.map(el => {
    const index = authorSelectTable.value.participantList.findIndex(
      part => part.id === el.partakeUnitCode
    );
    if (index !== -1) {
      authorSelectTable.value.participantList.splice(index, 1);
    }
  });
  publishDeptsCatch.value = publishDeptsCatch.value.filter(item => {
    if (item.partakeUnitName !== event) {
      return item;
    }
  });
  deptTreePartakeRef.value.setCheckedKeys(
    publishDeptsCatch.value.map(item => {
      return item.partakeUnitCode;
    })
  );
};

//选择内外部单位
const handleCheckChangePartake = (
  checkedNodes,
  checkedKeys,
  halfCheckedNodes,
  halfCheckedKeys
) => {
  console.log(checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys);
  const res = deptTreePartakeRef.value.getCheckedNodes();
  const newData =
    res.length &&
    res.map(item => {
      return {
        partakeUnitCode: item.id,
        partakeUnitName: item.deptDescShrt,
        isEmp: item.isEmp,
        isDept: "0"
      };
    });
  if (res.length) {
    publishDeptsCatch.value = newData;
    publishDepts.value = newData.map(el => el.partakeUnitName);
  } else {
    publishDeptsCatch.value = [];
    publishDepts.value = [];
  }
  publishDeptsCatch.value.map(el => {
    const index = authorSelectTable.value.participantList.findIndex(
      part => part.id === el.partakeUnitCode
    );
    if (index === -1) {
      authorSelectTable.value.participantList.push({
        id: el.partakeUnitCode,
        userId: el.partakeUnitCode,
        name: el.partakeUnitName,
        isEmp: el.isEmp,
        isDept: "0"
      });
    }
  });
  model.formData.author = publishDeptsCatch.value.concat(
    authorSelectTable.value.participantList
  );
};

const id = route.query.id;
const source = route.query.source; //驳回到第一步，然后待办里面点击可以重新调到该页面，重新走流程审批
const isEdit = route.query.mode === "edit" ? true : false;
if (id) {
  model.mode = "Edit";
  getData(id);
}
initDeptList();
initPrincipalCompanyList();
getProjectList();
</script>

<style lang="scss" scoped>
.content {
  .card-box--headerwrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-box--setbtn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 140px;
  }
}

.apply-select-table {
  display: flex;
  flex-wrap: wrap;
}
</style>
